package save_data

import (
	"database/sql"
	"fmt"
	"study5/jysp/model"
	_ "github.com/go-sql-driver/mysql"
)

const DB_NAME = "mysql"
const DB_SOURCE = "root:123456@tcp(127.0.0.1:3306)/t1"

var db *sql.DB

func init(){
initDB()

}


func initDB(){
	var err error
	db,err = sql.Open(DB_NAME,DB_SOURCE)
	if err != nil{
		fmt.Println(err)
	}

	_,err = db.Exec("DROP TABLE IF EXISTS `jy`")
	if err != nil{
		panic(err)
	}

	_,err = db.Exec(`CREATE TABLE jy (
  	id int(11) NOT NULL AUTO_INCREMENT,
  	nick_name varchar(50) DEFAULT NULL,
  	age int(3) DEFAULT NULL,
 	 marriage varchar(20) DEFAULT NULL,
 	 height varchar(10) DEFAULT NULL,
 	 education varchar(10) DEFAULT NULL,
 	 work_location varchar(50) DEFAULT NULL,
  	short_note varchar(200) DEFAULT NULL,
 	 match_condition varchar(200) DEFAULT NULL,
  	PRIMARY KEY (id)
	) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8`)
	if err != nil{
		panic(err)
	}
}

type MyqlSaver struct {

}

func NewMysqlSaver() *MyqlSaver{
	return &MyqlSaver{}
}

func (s *MyqlSaver) Save(list []*model.ListUserInfo) (num int,err error){
	stmt,err := db.Prepare("insert into jy (nick_name,age,marriage,height,education,work_location,short_note,match_condition) values (?,?,?,?,?,?,?,?)")
	if err != nil{
		return
	}

	defer stmt.Close()
	for _,item := range list{
		_,err = stmt.Exec(item.Nickname,item.Age,item.Marriage,item.Height,item.Education,item.WorkLocation,item.Shortnote,item.MatchCondition)
		if err != nil{
			return
		}
		num++
	}
	return
}